import { Upload, message } from 'antd';
import { RcFile } from 'antd/es/upload';
import React, { useState, useEffect, useCallback } from 'react';

import userService, { UserInfoReq } from '@/api/services/userService';
import { SvgIcon } from '@/components/icon';
import Modals from '@/components/modals/Modals';
import ImageDisplay from '@/components/work-modal/components/ImageDisplay';
import { MongoImageTypeEnum } from '@/pages/chat/tools/constants';
import { useUserActions, useUserInfo } from '@/store/userStore';
import { compressImgFileAndUpload } from '@/types/app/api';

import type { UploadProps } from 'antd';

interface UserModalProps {
  visible: boolean;
  onCancel: () => void;
}

const UserModal: React.FC<UserModalProps> = ({ visible, onCancel }) => {
  const [userInfo, setUserInfo] = useState<UserInfoReq>({
    id: '',
    userName: '',
    avatar: '',
    identityId: '',
    groupName: '',
    groupId: '',
    roleList: [],
  });
  const [avatarLoading, setAvatarLoading] = useState(false);
  const { updateUserDetailInfo } = useUserActions();
  const currentUser = useUserInfo();

  // 图片上传前的验证
  const beforeUpload = (file: RcFile) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件！');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB！');
      return false;
    }
    return true;
  };

  const handleAvatarUpload = async (file: File) => {
    setAvatarLoading(true);
    try {
      const src = await compressImgFileAndUpload({
        type: MongoImageTypeEnum.userAvatar,
        file,
        maxW: 300,
        maxH: 300,
      });
      const url = new URL(src);
      const path = url.pathname.replace('//', '/');
      await updateUserAvatar(path);

      message.success('头像上传成功');
    } catch (error) {
      console.error('头像上传失败:', error);
      message.error('头像上传失败');
    } finally {
      setAvatarLoading(false);
    }
  };

  const updateUserAvatar = async (avatarUrl: string) => {
    try {
      await userService.updateUserInfo(userInfo.id, avatarUrl);
      setUserInfo((prev) => ({
        ...prev,
        avatar: avatarUrl,
      }));

      // 同步更新到userStore
      updateUserDetailInfo({ avatar: avatarUrl });
    } catch (error) {
      console.error('更新用户头像失败:', error);
      throw error;
    }
  };

  const fetchUser = useCallback(async () => {
    try {
      if (!currentUser?._id) {
        console.warn('No user ID available for fetching user info');
        return null;
      }

      const userInfo = await userService.getUserInfo(currentUser._id);
      return userInfo;
    } catch (error) {
      console.error('Failed to fetch user info:', error);
      throw error;
    }
  }, [currentUser?._id]);

  const fetchUserInfo = useCallback(async () => {
    try {
      const response = await fetchUser();
      if (!response) {
        console.warn('No user data received');
        return;
      }

      const userDetail = Array.isArray(response) ? response[0] : response;
      setUserInfo(userDetail);

      if (userDetail) {
        updateUserDetailInfo({
          avatar: userDetail.avatar,
        });
      }
    } catch (error) {
      console.error('Failed to fetch User info:', error);
    }
  }, [fetchUser, updateUserDetailInfo]);

  useEffect(() => {
    if (visible) {
      fetchUserInfo();
    }
  }, [visible, fetchUserInfo]);

  const uploadProps: UploadProps = {
    name: 'file',
    showUploadList: false,
    beforeUpload,
    customRequest: ({ file }) => handleAvatarUpload(file as File),
    accept: 'image/*',
  };

  return (
    <Modals title="用户信息" open={visible} onCancel={onCancel} footer={null} width={523}>
      <div className="mb-6 flex items-start space-y-6">
        <div className="mt-6 flex w-2/5 flex-shrink-0 flex-col items-center gap-7 text-center">
          {userInfo?.avatar ? (
            <ImageDisplay
              src={userInfo?.avatar || ''}
              alt="avatar"
              containerClassName="rounded-[50%] w-[100px] h-[100px] border-none"
            />
          ) : (
            <SvgIcon icon="ic-avatar" size="100" className="mr-2 rounded-md" />
          )}
          <Upload {...uploadProps}>
            <div className="hover:bg-gray-50 flex h-[32px] w-[108px] cursor-pointer items-center justify-center rounded-sm border !border-[#00000026] !text-[#000]">
              <SvgIcon icon="icon-upload" color="#00000073" size="14" className="mr-1" />
              <div className="text-center text-[#474C5F]">
                {avatarLoading ? '上传中...' : '上传头像'}
              </div>
            </div>
          </Upload>
        </div>
        <div className="w-3/5 space-y-4">
          <div>
            <div className="mb-1 font-medium text-black">名称</div>
            <div className="text-gray-600">{userInfo?.userName || '-'}</div>
          </div>
          <div>
            <div className="mb-1 font-medium text-black">学/工号</div>
            <div className="text-gray-600">{userInfo?.identityId || '-'}</div>
          </div>
          <div>
            <div className="mb-1 font-medium text-black">所属组织</div>
            <div className="text-gray-600">{userInfo?.groupName || '-'}</div>
          </div>
          <div>
            <div className="mb-1 font-medium text-black">角色</div>
            <div className="text-gray-600">
              {Array.isArray(userInfo?.roleList) ? userInfo.roleList.join('、') : '-'}
            </div>
          </div>
        </div>
      </div>
    </Modals>
  );
};

export default UserModal;
